<?php

use think\Model;
use think\Request;

class sina extends Model{
	//回调地址
	public $returnUrl;
	// 应用id
	public $appId;
	// 应用密室
	public $appSecret;

	/**
     * 构造函数
     */
	public function __construct(){
		$this->returnUrl 	= 'http://'.$_SERVER['HTTP_HOST'].'/index.php/book/member.login/callback/oauth/sina';
		$this->appId 		= '';
		$this->appSecret 	= '';
	}

	//构造要请求的参数数组，无需改动
	public function login(){
		$_SESSION['state'] = md5(uniqid(rand(), TRUE));
		//拼接URL
		$dialog_url = "https://api.weibo.com/oauth2/authorize?"
			. "client_id=".$this->appId
			. "&redirect_uri=".urlencode($this->returnUrl)
			. "&state=".$_SESSION['state'];
		echo("<script> top.location.href='" . $dialog_url . "'</script>");
		exit;
	}

    /**
     * 新浪微博 登录返回  参考手册 http://open.weibo.com/wiki/%E6%8E%88%E6%9D%83%E6%9C%BA%E5%88%B6
     * @return boolean
     */
	public function respon(){
		if($_REQUEST['state'] == $_SESSION['state']){
			$code = $_REQUEST["code"];
			//拼接URL
			$token_url = "https://api.weibo.com/oauth2/access_token?"
				. "client_id=" . $this->appId
				. "&client_secret=" . $this->appSecret
				. "&redirect_uri=" . urlencode($this->returnUrl)
				. "&grant_type=authorization_code"
				. "&code=" . $code;
			// 获取 Access Token
			$response = json_decode($this->get_contents($token_url, 1));
			if (isset($response->error)){
				echo "<h3>error:</h3>" . $response->error;
				echo "<h3>msg  :</h3>" . $response->error_description;
				exit;
			}

			// 使用Access Token来获取授权相关信息
			$graph_url = "https://api.weibo.com/oauth2/get_token_info?access_token=".$response->access_token;
			$user  = json_decode($this->get_contents($graph_url, 1));
			if (isset($user->error))
			{
				echo "<h3>error:</h3>" . $user->error;
				echo "<h3>msg  :</h3>" . $user->error_description;
				exit;
			}

			// 使用授权相关信息来获取用户信息
			$user_info_url = 'https://api.weibo.com/2/users/show.json?'.http_build_query(['access_token' => $response->access_token, 'uid' => $user->uid]);
			$user_info = json_decode($this->get_contents($user_info_url));
			$_SESSION['state'] = null; // 验证SESSION
			return [
				'openid' 	=> $user_info->id,// 新浪微博 uid
				'oauth' 	=> 'sina',
				'nickname' 	=> $user_info->screen_name,
				'avatar' 	=> $user_info->avatar_large,
			];
		}else{
			return false;
		}
	}

	public function get_contents($url, $method_post = 0){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, $method_post);
		$response =  curl_exec($ch);
		curl_close($ch);

		//-------请求为空
		if(empty($response)){
			exit("50001");
		}
		return $response;
	}
}